package com.et.sale.order.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.et.common.time.DateUtil;
import com.et.sale.jifen.dao.JifenDao;
import com.et.sale.member.dao.MemberDao;
import com.et.sale.order.dao.OrderDao;
import com.et.sale.order.entity.OrderEntity;
import com.et.sale.order.service.OrderService;
import com.et.sale.ticket.dao.TicketDao;
import com.et.sale.user.dao.UserDao;
import com.et.sale.user.entity.UserEntity;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao dao;

	@Autowired
	private TicketDao ticketDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private JifenDao jifenDao;
	
	

	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public int addSave(OrderEntity entity) {
		
		
		int ticketId = entity.getTicketId();

		// 你买了一张票 如果是50元
		int price = ticketDao.findById(ticketId).getPrice();

		// 票的数量 2
		int qty = entity.getQty();

		// 总的价格 100 * 1
		Double total = price * qty*1.00;
		
		
		Integer userId = entity.getUserId();
		
		
		UserEntity userEntity = userDao.findByUserId(userId);
		Integer memberId = userEntity.getMemberId();
		
		
		Double discount = memberDao.findByMemberId(memberId).getDiscount();
		
		//本次购买送的积分  １： 会得到对应的积分
		Double jifen = total /100;
		
		UserEntity preUser = userDao.findByUserId(userId);
		
		//  因为开始你有100积分 那么你现在一共有： 110 积分
		Double totalJifen =jifen  + preUser.getJifen();
		
		//你一共要放多少血 100 * 0.95  3： 折扣1000 *0.95 =950元 
		Double totalMoney = total * discount;
		
		Double money = 0.00;
		if(!StringUtils.isEmpty(entity.getShifoushiyongjifen())){
			//使用积分 积分可以当多少钱用 2： 你的积分成转化成钱 然后 去抵买门票的钱
			money = totalJifen/10;
			
			//4：那么我支付多少钱
			totalMoney =totalMoney - money;
		}
		
		
		Double shengyu  =preUser.getBalance() - totalMoney;
		
		
		UserEntity user = new UserEntity();
		user.setId(userId);
		user.setBalance(shengyu);
		user.setMemberId(memberId);
		
		user.setJifen(0.00);
		
		userDao.update(user);
		
		
		
		
		
		entity.setTotalMoney(totalMoney);
		
		entity.setCreateDate(DateUtil.getDate());
		
		int count = dao.addSave(entity);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("jifen", jifen);
		map.put("orderId", entity.getId());
		jifenDao.addSave(map );
		
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("userId", userId);
		map2.put("jifen", -totalJifen);
		map2.put("orderId", entity.getId());
		jifenDao.addSave(map2 );
		
		
		
		return count;
	}

}
